package num463;

/**
 * @author : DuJiabao
 * @Project : sword-finger-offer
 * @Time : 2021/5/9 20:34
 * @Desc :
 */
public class Solution {
  public int islandPerimeter(int[][] grid) {
    int lengthNum = 0;
    int height = grid.length;
    int width = grid[0].length;

    for (int h = 0; h < height; h++) {
      for (int w = 0; w < width; w++) {
        if (grid[h][w] == 1) {
          lengthNum += dfs(grid, h, w);
          System.out.println(lengthNum);
        }
      }
    }
    return lengthNum;
  }

  private int dfs(int[][] grid, int h, int w) {
    int res = 0;
    if ((h > 0 && grid[h - 1][w] == 0) || h == 0) res++;
    if ((w > 0 && grid[h][w - 1] == 0) || w == 0) res++;
    if ((h < grid.length - 1 && grid[h + 1][w] == 0) || h == grid.length - 1) res++;
    if ((w < grid[0].length - 1 && grid[h][w + 1] == 0) || w == grid[0].length - 1) res++;
    return res;
  }


  public static void main(String[] args) {
    int[][] grid = {{0, 1, 0, 0}, {1, 1, 1, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}};
    int res = new Solution().islandPerimeter(grid);
    System.out.println(res);
  }
}
